package sziit.znk.factory;

import sziit.znk.utils.IfComponent;
import sziit.znk.utils.importothers.ClassUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

public class ScanAutoWireBean {

    private static Map<String, Object> beanContainer = null;

    static {
        beanContainer = BeanFactory.getBeanContainer();
    }

    public ScanAutoWireBean(String packageName) {

        List<Class<?>> classes = ClassUtil.getClasses(packageName);
        try {
            for (Class<?> aClass : classes) {
                Annotation[] annotations = aClass.getDeclaredAnnotations();
                boolean flag = false;
                for (Annotation annotation : annotations) {
                    if (IfComponent.havingComponentAnnotation(annotation)) flag = true;
                    if (flag) {
                        Field[] fields = aClass.getDeclaredFields();
                        for (Field field : fields) {
                            if (field.getAnnotation(sziit.znk.annotation.bean.Autowire.class) != null) {
                                field.setAccessible(true);
                                String name = aClass.getName();
                                String[] split = name.replace(".", "/").split("/");
                                int length1 = split.length;
                                String od = split[length1 - 1].substring(0, 1).toLowerCase() + split[length1 - 1].substring(1);
                                Object o = beanContainer.get(od);
                                String typeName = field.getType().getName();
                                String[] splits = typeName.replace(".", "/").split("/");
                                int length = splits.length;
                                String id = splits[length - 1].substring(0, 1).toLowerCase() + splits[length - 1].substring(1);
                                field.set(o, beanContainer.get(id));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
